{% extends "base.html" %}

{% block head %}
<style>
    :root {
        --primary-color: #1976d2;
        --primary-hover: #1565c0;
        --border-color: #e0e0e0;
        --light-gray: #f5f5f5;
        --text-color: #333;
        --shadow-color: rgba(0, 0, 0, 0.1);
    }

    body {
        color: var(--text-color);
        background-color: #f8f9fa;
    }

    .container {
        min-width: 800px;
        margin: 0 auto;
    }

    /* 卡片样式 */
    .card {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 4px var(--shadow-color);
        padding: 20px;
        margin-bottom: 20px;
    }

    .card-header {
        margin: -20px -20px 20px;
        padding: 15px 20px;
        background: var(--light-gray);
        border-radius: 8px 8px 0 0;
        border-bottom: 1px solid var(--border-color);
    }

    .card-header h2 {
        margin: 0;
        font-size: 1.5rem;
        color: var(--primary-color);
    }

    .card-header .card-header_text {
        font-size: 12px;
        font-weight: 400;
        color: rgba(128, 128, 128, 1);
        margin-top: 10px;
    }

    /* 表格容器样式优化 */
    .table-wrapper {
        position: relative;
        background: white;
    }

    .table-container {
        width: 100%;
        overflow-x: auto;
        position: relative;
        max-height: 600px;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: var(--primary-color) var(--light-gray);
    }

    /* 自定义滚动条样式 */
    .table-container::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    .table-container::-webkit-scrollbar-track {
        background: var(--light-gray);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb {
        background: var(--primary-color);
        border-radius: 4px;
    }

    .table-container::-webkit-scrollbar-thumb:hover {
        background: var(--primary-hover);
    }

    /* 表格样式优化 */
    .result-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        margin: 0;
        font-size: 12px;
        min-width: 1200px;
    }

    .result-table th {
        background: #e6f7ff;
        color: #0050b3;
        font-weight: normal;
        position: sticky;
        top: 0;
        z-index: 1;
        white-space: normal;
        word-break: break-word;
        min-width: 120px;
        height: auto;
        padding: 8px 6px;
        line-height: 1.4;
    }

    .result-table td {
        border: 1px solid #d9d9d9;
        padding: 6px 4px;
        text-align: left;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 150px;
    }

    .result-table tr:nth-child(even) {
        background: #f5faff;
    }

    .result-table td:hover {
        overflow: visible;
        white-space: normal;
        word-break: break-all;
        position: relative;
        z-index: 2;
        background: #fff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    /* 滑动指示器 */
    .scroll-indicator {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: white;
        padding: 8px;
        border-radius: 4px;
        font-size: 12px;
        opacity: 0;
        transition: opacity 0.3s;
        pointer-events: none;
        z-index: 99;
    }

    .scroll-indicator.visible {
        opacity: 1;
    }

    /* 分页控件美化 */
    .pagination-container {
        background: white;
        padding: 15px;
        border-top: 1px solid var(--border-color);
        border-radius: 0 0 8px 8px;
        display: flex;
        justify-content: flex-end;
        margin-top: 12px;
        gap: 8px;
    }

    #total-records {
        color: #555;
        font-size: 13px;
        margin-right: 16px;
    }

    .pagination {
        display: flex;
        justify-content: center;
        gap: 8px;
    }

    .pagination button {
        padding: 4px 12px;
        border: 1px solid #d9d9d9;
        border-radius: 4px;
        background: #fff;
        cursor: pointer;
    }

    .pagination button:disabled {
        background: #f5f5f5;
        cursor: not-allowed;
    }

    .pagination button.active {
        background: #1890ff;
        color: white;
        border-color: #1890ff;
    }

    .pagination-ellipsis {
        color: #555;
        padding: 0 8px;
    }

    /* 按钮和表单样式 */
    .form-group {
        margin-bottom: 20px;
    }

    .form-group .button-group {
        margin: 0;
    }

    /* 按钮基础样式 */
    .btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 8px 16px;
        font-size: 14px;
        font-weight: 500;
        text-align: center;
        text-decoration: none;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
        border: 1px solid transparent;
        height: 32px;
        line-height: 1;
        margin: 0;
        white-space: nowrap;
    }

    .btn-primary {
        background-color: var(--primary-color);
        color: white;
        border: none;
    }

    .btn-primary:hover {
        background-color: var(--primary-hover);
    }

    .btn-outline-primary {
        background-color: transparent;
        border-color: var(--primary-color);
        color: var(--primary-color);
    }

    .btn-outline-primary:hover {
        background-color: var(--primary-color);
        color: white;
    }

    /* 按钮组样式 */
    .button-group {
        display: flex;
        align-items: center;
        gap: 10px;
        margin: 0;
    }

    .action-buttons {
        display: flex;
        align-items: center;
        gap: 15px;
        margin-bottom: 20px;
    }

    /* 状态样式 */
    .dict-status {
        display: inline-block;
        padding: 4px 8px;
        border-radius: 4px;
        font-size: 14px;
        margin-left: 10px;
    }

    .dict-status.exists {
        background-color: #e8f5e9;
        color: #2e7d32;
    }

    .dict-status.not-exists {
        background-color: #ffebee;
        color: #c62828;
    }

    .dict-status.analyzing {
        background-color: #fff3e0;
        color: #ef6c00;
        animation: pulse 1.5s infinite;
    }

    @keyframes pulse {
        0% { opacity: 1; }
        50% { opacity: 0.6; }
        100% { opacity: 1; }
    }

    /* 其他辅助样式 */
    .loading {
        display: none;
        text-align: center;
        margin: 20px 0;
    }

    .loading.active {
        display: block;
    }

    .error-message {
        color: red;
        margin: 10px 0;
        display: none;
    }

    .field-select-btn {
        margin-left: 12px;
    }

    .download-btn {
        margin-top: 10px;
        display: none;
    }

    /* 模态框样式 */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }

    .modal.visible {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .modal-content {
        background-color: white;
        padding: 24px;
        border-radius: 8px;
        width: 90%;
        max-width: 800px;
        max-height: 90vh;
        overflow-y: auto;
        position: relative;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 16px;
        border-bottom: 1px solid var(--border-color);
    }

    .modal-title {
        font-size: 20px;
        font-weight: 600;
        color: var(--text-color);
        margin: 0;
    }

    .modal-close {
        background: none;
        border: none;
        font-size: 24px;
        cursor: pointer;
        color: #666;
        padding: 4px;
        line-height: 1;
    }

    .modal-close:hover {
        color: var(--primary-color);
    }

    .modal-body {
        max-height: 400px;
        overflow-y: auto;
        padding: 10px 0;
    }

    .modal-footer {
        margin-top: 20px;
        padding-top: 15px;
        border-top: 1px solid #eee;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    /* 字段选择网格样式 */
    .field-selection-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 10px;
        margin-top: 10px;
    }

    .field-checkbox {
        display: flex;
        align-items: center;
        padding: 8px;
        background: var(--light-gray);
        border-radius: 4px;
        cursor: pointer;
        transition: background-color 0.2s;
    }

    .field-checkbox:hover {
        background-color: var(--menu-hover);
    }

    .field-checkbox input {
        margin-right: 8px;
    }

    .field-checkbox label {
        font-size: 14px;
        color: var(--text-color);
        cursor: pointer;
    }

    .select-all-btn {
        margin-bottom: 10px;
    }

    /* 确认对话框样式 */
    .dialog-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }

    .confirm-dialog {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        z-index: 1001;
        width: 300px;
    }

    .confirm-dialog h3 {
        margin: 0 0 15px 0;
        color: var(--text-color);
    }

    .confirm-dialog p {
        margin: 0 0 20px 0;
        color: #666;
    }

    .dialog-buttons {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    /* 按钮样式补充 */
    .btn-sm {
        padding: 4px 8px;
        font-size: 12px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="card">
        <div class="card-header">
            <h2>一张发票多次报销模型</h2>
            <div class="card-header_text">
                模型重点关注是否存在利用一张住宿发票多次报销的问题。利用报销住宿发票、以发票编号为组、计算发票编号出现的报销单数量，筛查是否存在一张发票多次报销的疑点线索。
            </div>
        </div>

        <!-- 操作按钮组 -->
        <div class="action-buttons">
            <div>
                <button type="button" class="btn btn-primary" onclick="showAnalysisConfirm()">分析数据</button>
                <span id="analysisStatus" class="dict-status"></span>
            </div>
            <button type="button" class="btn btn-primary" onclick="loadExistingData()">加载已有数据</button>
        </div>

        <!-- 字段选择和下载按钮 -->
        <div class="form-group">
            <div class="button-group">
                <button type="button" class="btn btn-outline-primary" onclick="openFieldSelection()" id="fieldSelectBtn" style="display: none;">选择显示字段</button>
                <button type="button" class="btn btn-outline-primary" onclick="downloadExcel()" id="downloadBtn" style="display: none;">下载Excel</button>
            </div>
        </div>

        <!-- 错误消息 -->
        <div id="errorMessage" class="error-message"></div>

        <!-- 加载动画 -->
        <div id="loading" class="loading">
            <div class="loading-spinner"></div>
            正在加载数据，请稍候...
        </div>
    </div>

    <!-- 结果表格 -->
    <div id="resultContainer" class="card" style="display: none;">
        <div class="table-wrapper">
            <div class="scroll-indicator">向右滑动查看更多</div>
            <div class="table-container">
                <table class="result-table">
                    <thead>
                        <tr id="tableHeader">
                            <!-- 表头将通过JavaScript动态生成 -->
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- 数据行将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
            <div class="pagination-container">
                <div id="total-records"></div>
                <div class="pagination" id="pagination"></div>
            </div>
        </div>
    </div>

    <!-- 字段选择模态框 -->
    <div id="fieldSelectionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">选择显示字段</h3>
                <button type="button" class="modal-close" onclick="closeFieldSelection()">&times;</button>
            </div>
            <div class="modal-body">
                <button type="button" class="btn btn-outline-primary btn-sm select-all-btn" onclick="toggleSelectAllFields()">全选/取消全选</button>
                <div class="field-selection-grid" id="fieldCheckboxes">
                    <!-- 字段选择项将通过JavaScript动态生成 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-primary" onclick="closeFieldSelection()">取消</button>
                <button type="button" class="btn btn-primary" onclick="applyAndCloseFieldSelection()">确定</button>
            </div>
        </div>
    </div>

    <!-- 确认对话框 -->
    <div class="dialog-overlay" id="dialogOverlay"></div>
    <div class="confirm-dialog" id="confirmDialog">
        <h3>确认分析</h3>
        <p>是否确定要重新分析数据？</p>
        <div class="dialog-buttons">
            <button class="btn btn-outline-primary" onclick="closeDialog()">取消</button>
            <button class="btn btn-primary" onclick="confirmAnalysis()">确定</button>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    let currentData = [];
    let selectedFields = new Set();
    let allFields = [];
    let currentPage = 1;
    const pageSize = 50;
    let totalPages = 0;

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        checkResultFileExists();
        initializeScrollIndicator();
    });

    // 检查结果文件是否存在
    async function checkResultFileExists() {
        try {
            const response = await fetch('/invoice-duplicate/check-result-file');
            const data = await response.json();
            
            if (data.exists) {
                updateAnalysisStatus('exists', '分析结果已存在');
                document.getElementById('fieldSelectBtn').style.display = 'inline-block';
                document.getElementById('downloadBtn').style.display = 'inline-block';
            } else {
                updateAnalysisStatus('not-exists', '暂无分析结果');
            }
        } catch (error) {
            console.error('检查文件状态时出错:', error);
            showError('检查文件状态时出错');
        }
    }

    // 更新分析状态显示
    function updateAnalysisStatus(status, text) {
        const statusElement = document.getElementById('analysisStatus');
        statusElement.className = 'dict-status ' + status;
        statusElement.textContent = text;
    }

    // 显示分析确认对话框
    function showAnalysisConfirm() {
        document.getElementById('dialogOverlay').style.display = 'block';
        document.getElementById('confirmDialog').style.display = 'block';
    }

    // 关闭对话框
    function closeDialog() {
        document.getElementById('dialogOverlay').style.display = 'none';
        document.getElementById('confirmDialog').style.display = 'none';
    }

    // 确认分析
    async function confirmAnalysis() {
        closeDialog();
        try {
            updateAnalysisStatus('analyzing', '正在分析中...');
            const response = await fetch('/invoice-duplicate/generate-analysis');
            const data = await response.json();
            
            if (data.success) {
                updateAnalysisStatus('exists', '分析完成');
                document.getElementById('fieldSelectBtn').style.display = 'inline-block';
                document.getElementById('downloadBtn').style.display = 'inline-block';
                await loadExistingData();
            } else {
                updateAnalysisStatus('not-exists', '分析失败');
                showError(data.message || '分析过程中出现错误');
            }
        } catch (error) {
            console.error('分析数据时出错:', error);
            updateAnalysisStatus('not-exists', '分析失败');
            showError('分析过程中出现错误');
        }
    }

    // 加载已有数据
    async function loadExistingData() {
        try {
            document.getElementById('loading').classList.add('active');
            document.getElementById('resultContainer').style.display = 'none';
            
            const response = await fetch('/invoice-duplicate/get-data');
            const result = await response.json();
            
            if (result.success && result.data) {
                currentData = result.data;
                if (currentData.length > 0) {
                    allFields = result.all_columns.map(column => ({
                        id: column,
                        name: column
                    }));
                    if (selectedFields.size === 0) {
                        selectedFields = new Set(allFields);
                    }
                    updateTable();
                    document.getElementById('resultContainer').style.display = 'block';
                }
            } else {
                showError(result.error || '无法加载数据');
            }
        } catch (error) {
            console.error('加载数据时出错:', error);
            showError('加载数据时出错');
        } finally {
            document.getElementById('loading').classList.remove('active');
        }
    }

    // 更新表格显示
    function updateTable() {
        if (!currentData || currentData.length === 0) return;

        // 更新表头
        const headerRow = document.getElementById('tableHeader');
        headerRow.innerHTML = '';
        Array.from(selectedFields).forEach(field => {
            const th = document.createElement('th');
            th.textContent = field.name;
            headerRow.appendChild(th);
        });

        // 计算分页
        totalPages = Math.ceil(currentData.length / pageSize);
        const start = (currentPage - 1) * pageSize;
        const end = Math.min(start + pageSize, currentData.length);
        const pageData = currentData.slice(start, end);

        // 更新表格内容
        const tbody = document.getElementById('tableBody');
        tbody.innerHTML = '';
        pageData.forEach(row => {
            const tr = document.createElement('tr');
            Array.from(selectedFields).forEach(field => {
                const td = document.createElement('td');
                td.textContent = row[field.id] || '';
                tr.appendChild(td);
            });
            tbody.appendChild(tr);
        });

        // 更新分页控件
        updatePagination();
        
        // 更新记录总数显示
        document.getElementById('total-records').textContent = `共 ${currentData.length} 条记录`;
    }

    // 更新分页控件
    function updatePagination() {
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';

        // 上一页按钮
        const prevButton = document.createElement('button');
        prevButton.textContent = '上一页';
        prevButton.disabled = currentPage === 1;
        prevButton.onclick = () => goToPage(currentPage - 1);
        pagination.appendChild(prevButton);

        // 页码按钮
        for (let i = 1; i <= totalPages; i++) {
            if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
                const pageButton = document.createElement('button');
                pageButton.textContent = i;
                pageButton.className = i === currentPage ? 'active' : '';
                pageButton.onclick = () => goToPage(i);
                pagination.appendChild(pageButton);
            } else if (i === currentPage - 3 || i === currentPage + 3) {
                const ellipsis = document.createElement('span');
                ellipsis.textContent = '...';
                ellipsis.className = 'pagination-ellipsis';
                pagination.appendChild(ellipsis);
            }
        }

        // 下一页按钮
        const nextButton = document.createElement('button');
        nextButton.textContent = '下一页';
        nextButton.disabled = currentPage === totalPages;
        nextButton.onclick = () => goToPage(currentPage + 1);
        pagination.appendChild(nextButton);
    }

    // 跳转到指定页
    function goToPage(page) {
        if (page >= 1 && page <= totalPages) {
            currentPage = page;
            updateTable();
        }
    }

    // 修改下载Excel函数
    async function downloadExcel() {
        if (selectedFields.size === 0) {
            alert('请至少选择一个字段');
            return;
        }

        const params = new URLSearchParams();
        Array.from(selectedFields).forEach(field => {
            params.append('fields', field.id);
        });
        
        const downloadUrl = `/invoice-duplicate/download-excel?${params.toString()}`;
        
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.style.display = 'none';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    // 显示错误信息
    function showError(message) {
        const errorElement = document.getElementById('errorMessage');
        errorElement.textContent = message;
        errorElement.style.display = 'block';
        setTimeout(() => {
            errorElement.style.display = 'none';
        }, 5000);
    }

    // 初始化滚动指示器
    function initializeScrollIndicator() {
        const tableContainer = document.querySelector('.table-container');
        const indicator = document.querySelector('.scroll-indicator');
        
        if (tableContainer && indicator) {
            tableContainer.addEventListener('scroll', () => {
                if (tableContainer.scrollWidth > tableContainer.clientWidth) {
                    if (tableContainer.scrollLeft === 0) {
                        indicator.classList.add('visible');
                    } else {
                        indicator.classList.remove('visible');
                    }
                }
            });

            // 初始检查
            if (tableContainer.scrollWidth > tableContainer.clientWidth) {
                indicator.classList.add('visible');
            }
        }
    }

    // 打开字段选择模态框
    function openFieldSelection() {
        const modal = document.getElementById('fieldSelectionModal');
        modal.classList.add('visible');
        initializeFieldSelection();
    }

    // 关闭字段选择模态框
    function closeFieldSelection() {
        const modal = document.getElementById('fieldSelectionModal');
        modal.classList.remove('visible');
    }

    // 初始化字段选择
    function initializeFieldSelection() {
        const container = document.getElementById('fieldCheckboxes');
        container.innerHTML = '';
        
        allFields.forEach(field => {
            const div = document.createElement('div');
            div.className = 'field-checkbox';
            const input = document.createElement('input');
            input.type = 'checkbox';
            input.id = `field_${field.id}`;
            input.checked = Array.from(selectedFields).some(f => f.id === field.id);
            
            const label = document.createElement('label');
            label.htmlFor = `field_${field.id}`;
            label.textContent = field.name;
            
            div.appendChild(input);
            div.appendChild(label);
            container.appendChild(div);
        });
    }

    function toggleSelectAllFields() {
        const checkboxes = document.querySelectorAll('#fieldCheckboxes input[type="checkbox"]');
        const allChecked = Array.from(checkboxes).every(cb => cb.checked);
        checkboxes.forEach(checkbox => checkbox.checked = !allChecked);
    }

    function applyAndCloseFieldSelection() {
        const checkboxes = document.querySelectorAll('#fieldCheckboxes input[type="checkbox"]:checked');
        const newSelectedFields = new Set();
        
        checkboxes.forEach(checkbox => {
            const fieldId = checkbox.id.replace('field_', '');
            const field = allFields.find(f => f.id === fieldId);
            if (field) {
                newSelectedFields.add(field);
            }
        });
        
        if (newSelectedFields.size === 0) {
            alert('请至少选择一个字段');
            return;
        }
        
        selectedFields = newSelectedFields;
        updateTable();
        closeFieldSelection();
    }
</script>
{% endblock %}